package com.jinjiafeng.baselibrary.inject;

import android.app.Activity;
import android.view.View;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Time :18-4-20
 *
 * @author jinjiafeng
 */

public class ViewInject {
    public static void inject(Activity activity) {
        inject(new ViewFinder(activity), activity);
    }

    private static void inject(ViewFinder finder, Object obj) {
        injectView(finder, obj);
        injectEvent(finder, obj);
    }

    private static void injectView(ViewFinder finder, Object obj) {
        final Class<?> aClass = obj.getClass();
        final Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            final BindView bindView = field.getAnnotation(BindView.class);
            if (bindView != null) {
                final int value = bindView.value();
                final View view = finder.findViewById(value);
                field.setAccessible(true);
                try {
                    field.set(obj, view);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void injectEvent(ViewFinder finder, Object obj) {
        final Class<?> aClass = obj.getClass();
        final Method[] methods = aClass.getDeclaredMethods();
        for (Method method : methods) {
            final Onclick onclick = method.getAnnotation(Onclick.class);
            if (onclick != null) {
                final int[] values = onclick.value();
                if (values.length > 0) {
                    for (int value : values) {
                        final View view = finder.findViewById(value);
                        if (view != null) {
                            view.setOnClickListener(new DeclaredOnClickListener(obj, method));
                        }
                    }
                }
            }
        }
    }

    public static void inject(Object obj, View view) {
        inject(new ViewFinder(view), obj);
    }

    private static final class DeclaredOnClickListener implements View.OnClickListener {
        private final Object mObject;
        private final Method mMethod;

        public DeclaredOnClickListener(Object object, Method method) {
            mObject = object;
            mMethod = method;
        }

        @Override
        public void onClick(View v) {
            mMethod.setAccessible(true);
            try {
                mMethod.invoke(mObject, v);
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    mMethod.invoke(mObject);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
